<template>
  <div class="pop-dialog-container">
    <div class="pop-dialog-main">
      <el-form :inline="true" :model="parkingAreaQueryForm" ref="parkingAreaQueryFormRef" :rules="rules">
        <el-form-item label="车位号" prop="areaNumber">
          <el-input v-model="parkingAreaQueryForm.areaNumber" placeholder="请输入车位号" maxlength="32"></el-input>
        </el-form-item>
        <el-form-item label="楼栋名称" prop="buildingName">
          <el-input v-model="parkingAreaQueryForm.buildingName" placeholder="请选择楼栋名称" readonly="readonly">
            <template #suffix>
              <el-icon @click="findBuilding"><Search/></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="所在楼层" prop="floorNumber">
          <el-input v-model="parkingAreaQueryForm.floorNumber" placeholder="请输入所在楼层" maxlength="32"></el-input>
        </el-form-item>
        <el-form-item label="单元房号" prop="residentRoomNumber">
          <el-input v-model="parkingAreaQueryForm.residentRoomNumber" placeholder="请选择单元房号" readonly="readonly">
            <template #suffix>
              <el-icon @click="findRoom"><Search/></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="车牌" prop="licensePlate">
          <el-input v-model="parkingAreaQueryForm.licensePlate" placeholder="请输入车牌" maxlength="32"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="parkingAreaQueryForm.status" placeholder="请选择状态" class="select-custom">
            <el-option label="临停" :value="30"></el-option>
            <el-option label="业主" :value="10"></el-option>
            <el-option label="月租" :value="20"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="state.tableData"
        border
        v-loading="state.loading"
        size="small"
        header-cell-class-name="table-header-cell-font"
        cell-class-name="table-cell-font"
        @row-dblclick="parkingAreaSelected">
        <el-table-column prop="areaNumber" label="车位号"></el-table-column>
        <el-table-column prop="buildingName" label="楼栋名称"></el-table-column>
        <el-table-column prop="floorNumber" label="所在楼层"></el-table-column>
        <el-table-column prop="residentRoomNumber" label="单元房号"></el-table-column>
        <el-table-column prop="licensePlate" label="车牌"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template v-slot="{ row }">
            <div v-if="row.status === 30">临停</div>
            <div v-if="row.status === 10">业主</div>
            <div v-if="row.status === 20">月租</div>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-pagination">
        <el-pagination
          @current-change="changePage"
          :current-page="state.currentPage"
          :page-sizes="state.pageSizes"
          :page-size="state.pageSize"
          background
          layout="total, prev, pager, next, jumper"
          :total="state.total">
        </el-pagination>
      </div>
    </div>
    <div class="pop-dialog-footer">
      <el-row>
        <el-col :span="11" :offset="6">
          <div class="form-button-container">
            <el-button type="primary" @click="onBack">关闭</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog v-model="buildingSelectorVisible" v-if="buildingSelectorVisible" title="楼栋信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <building-selector @building-selected-event="handleBuildingSelectedEvent">
      </building-selector>
    </el-dialog>
    <el-dialog v-model="roomSelectorVisible" v-if="roomSelectorVisible" title="单元信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <room-selector @room-selected-event="handleRoomSelectedEvent">
      </room-selector>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { defineEmits, inject, onMounted, reactive, ref, toRefs } from 'vue'
import parkingAreaApi from '@/api/parkingAreaApi'
import type {ParkingAreaQueryForm} from "@/types/req/parkingAreaQueryForm";
import type {ParkingArea} from "@/types/resp/parkingArea";
import {type FormInstance} from "element-plus";
import type {Result} from "@/types/result";
import type {Page} from "@/types/page";
import { Search } from '@element-plus/icons-vue';
import BuildingSelector from "@/views/building/BuildingSelector.vue";
import RoomSelector from "@/views/room/RoomSelector.vue";

const parkingAreaQueryFormRef = ref<FormInstance | null>(null);
const parkingAreaQueryForm = reactive<ParkingAreaQueryForm>({
  areaNumber: '',
  buildingId: 0,
  buildingName: '',
  floorNumber: '',
  residentRoomId: 0,
  residentRoomNumber: '',
  licensePlate: '',
  status: undefined,
})
const buildingSelectorVisible = ref<boolean>(false)
const roomSelectorVisible = ref<boolean>(false)

const state = reactive({
  loading: false,
  tableData: [] as ParkingArea[], // 数据列表
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10, // 分页大小
  pageSizes: [10, 20, 50]
})

const dialogTop = ref<string>('')
const dialogWidth = ref<string>('')

const rules = reactive({
});

const emit = defineEmits<{
  (e: 'parkingAreaSelectedEvent', data?: {
    parkingAreaId: number,
    parkingAreaNumber: string,
    }): void;
}>()

onMounted(() => {
  onSearch()
  const globalState = inject('globalState', {} as { dialogWidth?: string, dialogTop?: string })
  if (!globalState) {
    throw new Error('globalState is not provided');
  }
  const globalStateRefs = toRefs(globalState)
  if (globalStateRefs.dialogWidth) {
    dialogWidth.value = globalStateRefs.dialogWidth.value || ''
  }
  if (globalStateRefs.dialogTop) {
    dialogTop.value = globalStateRefs.dialogTop.value || ''
  }
})

const getPageData = async () => {
  try {
    state.loading = true
    const resp: Result<Page<ParkingArea>> = await parkingAreaApi.find(parkingAreaQueryForm)
    if (resp && resp.code === 1) {
      if (resp.data) {
        const page: Page<ParkingArea> = resp.data
        if (page && page.list.length > 0) {
          state.tableData = page.list
          state.total = page.total
        }
      }
    }
  } catch (e) {
    console.log('获取数据异常', e)
  } finally {
    state.loading = false
  }
}
const onSearch = () => {
  getPageData()
}

const changePage = (val: number) => {
  state.currentPage = val
  getPageData()
}

const onReset = () => {
  if (parkingAreaQueryFormRef.value) {
    parkingAreaQueryFormRef.value.resetFields()
  }
  state.currentPage = 1
  getPageData()
}

const parkingAreaSelected = (row: ParkingArea) => {
  emit('parkingAreaSelectedEvent', {
    parkingAreaId: row.id,
    parkingAreaNumber: row.areaNumber,
  })
}

const findBuilding = () => {
  buildingSelectorVisible.value = true
}

const handleBuildingSelectedEvent = (selectedBuilding: any) => {
  buildingSelectorVisible.value = false
  if (selectedBuilding && 'buildingId' in selectedBuilding && parkingAreaQueryForm.buildingId !== selectedBuilding['buildingId']) {
    parkingAreaQueryForm.buildingId = selectedBuilding['buildingId']
    parkingAreaQueryForm.buildingName = selectedBuilding['buildingName']
  }
}
const findRoom = () => {
  roomSelectorVisible.value = true
}

const handleRoomSelectedEvent = (selectedRoom: any) => {
  roomSelectorVisible.value = false
  if (selectedRoom && 'residentRoomId' in selectedRoom && parkingAreaQueryForm.residentRoomId !== selectedRoom['residentRoomId']) {
    parkingAreaQueryForm.residentRoomId = selectedRoom['residentRoomId']
    parkingAreaQueryForm.residentRoomNumber = selectedRoom['residentRoomNumber']
  }
}

const onBack = () => {
  emit('parkingAreaSelectedEvent')
}
</script>

<style lang="scss">
</style>
